﻿using CubicFWNet.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CubicFWNet.Data.SystemManager
{
    public class RelevanceRepository : RepositoryBase<Relevance>
    {
        public void DeleteBy(string type,  Guid firstId)
        {
            Delete(u => u.FirstId == firstId && u.Type == type);
        }

        /// <summary>
        /// 删除关联
        /// </summary>
        /// <param name="key">关联标识</param>
        /// <param name="idMaps">关联的&lt;firstId, secondId&gt;数组</param>
        public void DeleteBy(string key, ILookup<Guid, Guid> idMaps)
        {
            foreach (var sameVals in idMaps)
            {
                foreach (var value in sameVals)
                {
                    Delete(u => u.Type == key && u.FirstId == sameVals.Key && u.SecondId == value);
                }
            }
        }

        /// <summary>
        /// 添加新的关联
        /// </summary>
        /// <param name="key">关联标识</param>
        /// <param name="idMaps">关联的&lt;firstId, secondId&gt;数组</param>
        public void AddRelevance(string key, ILookup<Guid, Guid> idMaps)
        {
            DeleteBy(key, idMaps);
            Insert((from sameVals in idMaps
                      from value in sameVals
                      select new Relevance
                      {
                          Id = Guid.NewGuid(),
                          CreatorId = Guid.NewGuid(),
                          Type = key,
                          FirstId = sameVals.Key,
                          SecondId = value,
                          CreateTime = DateTime.Now
                      }).ToList());
        }
    }
}
